package main

import (
	"flag"
	"fmt"
	"github.com/ghodss/yaml"
	"jsa/goods-rpc/goods"
	"jsa/goods-rpc/internal/config"
	"jsa/goods-rpc/internal/model"
	"jsa/goods-rpc/internal/server"
	"jsa/goods-rpc/internal/svc"
	"log"

	"github.com/BarnabyCharles/frame/app"
	config2 "github.com/BarnabyCharles/frame/config"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

func main() {
	flag.Parse()

	var c config.Config

	viper, err := config2.InitViper("etc", "./etc/goods.yaml", "yaml")
	if err != nil {
		log.Println(err)
		return
	}
	err = app.Init(
		viper.GetString("Nacos.serverName"),
		viper.GetString("Nacos.group"),
		viper.GetString("Nacos.namespaceId"),
		viper.GetString("Nacos.host"),
		viper.GetInt("Nacos.port"), "mysql")
	if err != nil {
		log.Println(err)
		return
	}
	nacosConfig, err := config2.GetNacosConfig(viper.GetString("Nacos.serverName"), viper.GetString("Nacos.group"))
	if err != nil {
		panic(err)
	}
	err = yaml.Unmarshal([]byte(nacosConfig), &c)
	if err != nil {
		panic(err)
	}
	ctx := svc.NewServiceContext(c)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		goods.RegisterGoodServer(grpcServer, server.NewGoodServer(ctx))

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})

	err = model.AutoMigrate()
	if err != nil {
		panic(err)
	}
	defer s.Stop()
	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
